package com.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

import com.core.initialize.AbsChannelInitializer;
import com.core.initialize.ServerChannelInitializer;

/**
 * 网络监听
 * @author King
 *
 */
public class NetAcceptor
{
	private EventLoopGroup bossGroup;
	private EventLoopGroup workerGroup;
	private ServerBootstrap b;
	private Channel channel;
	
	public NetAcceptor(EnginService engin,InetSocketAddress address)
	{
		AbsChannelInitializer handler = new ServerChannelInitializer();
		handler.setEnginService(engin);
		// handler
		this.bossGroup = new NioEventLoopGroup();
		this.workerGroup = new NioEventLoopGroup();
		this.b = new ServerBootstrap();
		b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
				.childHandler(handler);
		try {
			this.channel = b.bind(address).channel();
		} catch (Exception e) {
			 this.workerGroup.shutdownGracefully();
	         this.bossGroup.shutdownGracefully();
		}
	}
	
	/**
	 * 关闭服务器用
	 */
	public void shutdown()
	{
		this.channel.close();
		this.workerGroup.shutdownGracefully();
        this.bossGroup.shutdownGracefully();
	}

	public Channel getChannel() {
		return channel;
	}

}
